/**
  1.引入要调用GET,POST,PUT,DELETE方法
		const { postRequest } = require('../request.js')
	2.编写业务接口方法
		export const login = (params) => {
			return postRequest('/auth/login', params, true)
		}
	3.页面引入业务接口
		import { login } from '../../utils/api/modules/security.js'
	4.页面使用业务接口
		login({
			userName: 'admin',
			password: 123456
		}).then(res => {
			console.log('success', res)
		}).catch(error => {
			console.log('error', '出错啦～')
		}).finally(()=>{
			console.log('finally', '完成啦～')
		})
 */
import store from '@/store/index'

// 添加事件结束
Promise.prototype.finally = function(callback) {
	var Promise = this.constructor;
	return this.then(
		function(value) {
			Promise.resolve(callback()).then(
				function() {
					return value
				}
			)
		},
		function(reason) {
			Promise.resolve(callback()).then(
				function() {
					throw reason
				}
			)
		}
	)
}

const request = ({
	url,
	data,
	method,
	contentType
}) => {
	return new Promise((resolve, reject) => {
		const baseUrl="http://localhost:1110/ZHLG"
		uni.request({
			url: `${baseUrl}${url}`,
			data,
			method,
			header: {
				'content-type': contentType || 'application/json',
				'token': store.getters.getToken || ''
			},
			success: (res) => {
				// 返回成功提示信息
				if (res.statusCode === 200) {
					// 未登录拦截
					if (res.data.statusCode == 600) {
						uni.$router.login('reLaunch')
					} else if (res.data.statusCode == 500 || res.data.statusCode == 400) {
						reject(res.data)
					} else {
						resolve(res.data)
					}
				} else {
					if (res.statusCode === 401) {
						uni.$router.login('reLaunch')
					}
					// 返回错误提示信息
					reject(res.data)
				}
			},
			fail: (error) => {
				// 返回错误提示信息
				reject('系统开小差了，请联系在线客服哦~')
			},
			complete: () => {}
		})
	})
}

export const getRequest = (url, data) => {
	return request({
		url,
		data,
		method: 'GET'
	})
}

export const postRequest = (url, data) => {
	return request({
		url,
		data,
		method: 'POST',
		contentType:'application/json' 
	})
}

export const putRequest = (url, data, isForm) => {
	return request({
		url,
		data,
		method: 'PUT',
		contentType: !isForm ? 'application/json' : 'application/x-www-form-urlencoded'
	})
}

export const deleteRequest = (url, data) => {
	return request({
		url,
		data,
		method: 'DELETE'
	})
}

export const getBaseUrl = (url) => {
	const baseUrl = store.state.common.api
	return `${baseUrl}${url}`
}
